<script setup>
import axios from 'axios';
import {ref, reactive, onMounted, onUnmounted, computed} from 'vue';
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;  // 从环境变量获取基础 URL

const roomInfo = ref({
  room_id: 1,  // 初始ID设置，可以根据实际情况调整
  cur_temp:24,
  target_temp: 24,
  target_wind: 1,
  fee_rate: 0,
  cur_price: 0,
  total_price: 0,
  ac_status:'未开启'
});

let intervalId = null;

onMounted(() => {
  loadRoomInfo().then(() => {
    // 设置定时器，每3秒调用 getAcState 函数
    intervalId = setInterval(() => {
      getAcState();
    }, 3000);
  });
});



onUnmounted(() => {
  // 清除定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
});

async function loadRoomInfo() {
  try {
    const roomData = localStorage.getItem('room');
    if (roomData) {
      const room = JSON.parse(roomData);

      roomInfo.value.room_id = room.room_id;  // 更新room_id
      console.log(roomInfo.value.room_id);
      await getAcState();  // 现在使用更新后的room_id获取空调状态
    } else {
      console.error("No room data found in local storage.");
    }
  } catch (error) {
    console.error('加载房间信息出错:', error);
  }
}

// 打开空调
async function turnOnAC() {
  try {
    const response_status = await axios.get(`${apiBaseUrl}/guest/ac_status`, {params: {
        'room_id': roomInfo.value.room_id  // 确保这是正确的属性访问方式
      }});
    if(response_status.data.ac_status === "已开启" || response_status.data.ac_status === "等待中"){
      alert("空调已经是开启状态！");
    }else {
      const response = await axios.post(`${apiBaseUrl}/guest/open`, {
        room_id: roomInfo.value.room_id,
        target_wind: roomInfo.target_wind,
        target_temp: roomInfo.target_temp
      });
      await getAcState();
      console.log(response.data);
      if(response.data.status){
        roomInfo.fee_rate = response.data.fee_rate
        roomInfo.target_temp = response.data.target_temp
      }
    }
  } catch (error) {
    console.error('请求失败:', error);
  }
}

// 修改温度
async function changeTemperature(newTemp) {
  try {
    const params = {
      params: {
        room_id: roomInfo.value.room_id  // 确保这是正确的属性访问方式
      }
    };
    const response_status = await axios.get(`${apiBaseUrl}/guest/ac_status`, params);
    if(response_status.data.ac_status === "未开启"){
      alert("空调未运行");
    }else{
      const response_center = await axios.get(`${apiBaseUrl}/admin/center/get_center_state`);
      console.log(response_center.data.default_highest_temp);
      console.log(newTemp);
      if(newTemp > response_center.data.default_highest_temp || newTemp < response_center.data.default_lowest_temp){
        alert(newTemp);
      }else{
        const response = await axios.post(`${apiBaseUrl}/guest/temperature`, {
          room_id: roomInfo.value.room_id,
          new_temperature: newTemp
        });
        await getAcState();
        if(response.data.status){
          roomInfo.fee_rate = response.data.fee_rate
          roomInfo.target_temp = response.data.target_temp
        }
      }

    }

  } catch (error) {
    console.error('请求失败:', error);
  }
}

// 修改风速
async function changeWindSpeed(newSpeed) {
  try {
    const params = {
      params: {
        room_id: roomInfo.value.room_id  // 确保这是正确的属性访问方式
      }
    };
    const response_status = await axios.get(`${apiBaseUrl}/guest/ac_status`, params);
    if(response_status.data.ac_status === "未开启"){
      alert("请先开启空调");
    }else {
      if (newSpeed === 1 || newSpeed === 2 || newSpeed === 3) {
        console.log("newSpeed=",newSpeed)
        const response = await axios.post(`${apiBaseUrl}/guest/speed`, {
          room_id: roomInfo.value.room_id,
          new_speed: newSpeed
        });
        await getAcState();

        if (response.data.status) {
          roomInfo.fee_rate = response.data.fee_rate
          roomInfo.cur_temp = response.data.target_temp
        }
      }
    }
  } catch (error) {
    console.error('请求失败:', error);
  }
}
function changeTwoDecimal(floatvar)
{
  var f_x = parseFloat(floatvar);
  if (isNaN(f_x))
  {
    alert('function:changeTwoDecimal->parameter error');
    return false;
  }
  var f_x = Math.round(floatvar*100)/100;
  return f_x;
}

// 关闭空调
async function turnOffAC() {

  try {

    const response = await axios.post(`${apiBaseUrl}/guest/close`, {
      room_id: roomInfo.value.room_id
    });
    alert("空调已关闭,此次共消费"+ roomInfo.value.cur_price + "元");
    await getAcState();
    console.log(response.data);
    roomInfo.value.cur_price = 0;


  } catch (error) {
    console.error('请求失败:', error);
  }
}

async function getAcState() {
  try {
    const params = {
      params:{
        room_id: roomInfo.value.room_id  // 确保这是正确的属性访问方式
      }

    };
    const response = await axios.get(`${apiBaseUrl}/guest/ac_status`, params);
    console.log(response.data);
    roomInfo.value = response.data;
    roomInfo.value.cur_temp = changeTwoDecimal(response.data.cur_temp);
    roomInfo.value.cur_price = changeTwoDecimal(response.data.cur_price);
    roomInfo.value.total_price = changeTwoDecimal(response.data.total_price);

  } catch (error) {
    console.error('请求失败:', error);
  }
}

// 根据空调状态动态计算样式
const infoContainerStyle = computed(() => {
  return {
    backgroundColor: roomInfo.value.ac_status === '运行中' ? 'mediumpurple' : 'darkslateblue',  // 当空调未运行时使用暗色调
    padding: '10px',
    margin: '20px'
  };
});

const windSpeedDescription = computed(() => {
  const windSpeeds = {
    1: '低风',
    2: '中风',
    3: '高风'
  };
  return windSpeeds[roomInfo.value.target_wind] || '未知';
});

const modeDescription = computed(() => {
  const mode = {
    'cold': '制冷',
    'hot': '制热',
  };
  return mode[roomInfo.value.mode] || '未知';
});

</script>
<template>
  <div class="base">
    <div class="container">
      <div :style="infoContainerStyle" class="info-container" style="height: 280px; width: 400px">
        <div class="temperature-display">
          <div class="temperature-section">
            <div class="temperature-item">
              <h1 v-if="roomInfo.cur_temp !== '未知'">{{ roomInfo.cur_temp }}°</h1>
              <h1 v-else>{{ roomInfo.cur_temp }}</h1>
              <h3>实际温度</h3>
            </div>
            <div class="temperature-item">
              <h1 v-if="roomInfo.target_temp === 0"> 无 </h1>
              <h1 v-else-if="roomInfo.target_temp === '未知'"> 未知 </h1>
              <h1 v-else> {{ roomInfo.target_temp }}° </h1>
              <h3>目标温度</h3>
            </div>
          </div>
        </div>
        <div class="status-display">
          <div class="temperature-item">
            <div v-if="roomInfo.ac_status !== '未开启'">
              <h3>设定风速: {{ windSpeedDescription }} 当前费率: {{ roomInfo.fee_rate }}元/度</h3>
            </div>

            <h3>此次费用: {{ roomInfo.cur_price }}￥ 累计费用: {{ roomInfo.total_price }}￥</h3>
            <h3>{{ roomInfo.room_id }}客房</h3>
          </div>
        </div>
        <h1 style="position: absolute;top:100px;left: 45%;color: white"> -> </h1>
      </div>
      <div class="controls">
        <div class="adjustments">
          <button @click="turnOnAC()">开启空调</button>
          <button @click="turnOffAC()">关闭空调</button>
        </div>
        <div class="adjustments" >
          <div class="temperature-adjustment" >
            <button @click="changeTemperature(roomInfo.target_temp + 1)">温度 ↑</button>
            <button @click="changeTemperature(roomInfo.target_temp - 1)">温度 ↓</button>
          </div>
          <div class="speed-adjustment">
            <button @click="changeWindSpeed(roomInfo.target_wind + 1)">风速 ↑</button>
            <button @click="changeWindSpeed(roomInfo.target_wind - 1)">风速 ↓</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.base {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #372e4a;
  position: fixed;
  top: 0%;
  left: 0%;
  margin:auto 0;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 600px;
  background-color: #6A5ACD;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px; /* Adjust width as needed */
  height: 500px; /* Adjust height as needed */
  justify-content:center;

  border-radius: 15px;
  box-shadow:
      0px 0.9px 5.2px -43px rgba(0, 0, 0, 0.058),
      0px 3.8px 11.9px -43px rgba(0, 0, 0, 0.1),
      0px 10.3px 21.4px -43px rgba(0, 0, 0, 0.137),
      0px 25.3px 37.2px -43px rgba(0, 0, 0, 0.18),
      0px 74px 69px -43px rgba(0, 0, 0, 0.28)
;
  background-image: linear-gradient(to bottom right, rgb(118, 76, 163), rgb(92, 103, 211));

}

.temperature-display {
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 80%;
  align-items: center;
}

.temperature-section {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.temperature-item {
  text-align: center;
  color: white;
  margin-left:40px;
  margin-right: 40px;
}


h1{
  font-size: 44px;
}

h3{
  font-size:14px;
}

.status-display {
  margin-top: auto;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content:center;
  color: white;
  height: 20%;
  align-self: flex-end; /* 确保对齐到容器的底部 */
}

.controls {
  padding: 0 20px 20px 20px;
  width: 100%;
}

.adjustments {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.temperature-adjustment, .speed-adjustment {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

button {
  background-color: #9999FF;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px;
  cursor: pointer;
  flex-grow: 1;  /* 使按钮填充其容器 */
  margin: 5px;
}

button:hover {
  background-color: #B3B3FF;
}
</style>





